<template>
  <div class="flex min-h-screen bg-gray-50 pt-32">
      <!-- 卡片容器 -->
          <div class="relative mx-auto" style="width: 900px">
        <!-- 过场动画卡片 -->
        <div
          v-show="showTransition"
          class="relative rounded-lg mt-8 mb-8"
          style="background-color: #ececec; min-height: 580px; padding: 25px;"
        >
            <!-- 进度条区域 -->
            <div class="mt-20 flex items-center justify-center">
              <div class="w-[700px] h-[10px] rounded-full bg-gray-200 relative">
                <div 
                  class="h-full rounded-full absolute bg-[#429a9c]" 
                  :style="`width: 20%; left: ${transitionProgress}%`"
                ></div>
              </div>
            </div>
        </div>

                 <!-- 卡片1 -->
        <div
          v-show="!showTransition && currentCard === 0"
          class="relative rounded-lg mt-8 mb-8"
          style="background-color: #ececec; min-height: 580px; padding: 25px;"
        >
          <div class="rounded-lg bg-white p-6 shadow-lg" style="min-height: 530px">
          <!-- 标题与描述 -->
          <div class="mb-8">
            <h2 class="mb-2 text-2xl font-bold" style="color: #429a9c">Book en tid</h2>
            <p style="color: #444444">Hvilken klinik du vil gå til</p>
          </div>

          <!-- 进度条区域 -->
          <div class="mb-8 flex items-center space-x-25">
            <span class="text-sm font-medium whitespace-nowrap" style="color: #429a9c">Trin 1/6</span>
            <div class="flex-1 h-[10px] overflow-hidden rounded-full bg-gray-200">
              <div
                class="h-full rounded-full"
                style="background-color: #429a9c; width: 16.67%"
              ></div>
            </div>
          </div>

          <!-- 主内容区域 -->
          <div class="flex justify-between">
            <!-- 左侧：两个部分包装盒 -->
            <div class="overflow-hidden rounded-lg">
              <!-- 上部分 - 一段文字 -->
              <div>
                <div
                  class="flex w-[520px] h-[150px] cursor-pointer items-center justify-between bg-[#ececec] p-4 transition-colors hover:bg-[#e3e8e8]"
                >
                  <div class="flex flex-col space-y-2">
                    <span class="text-xl font-semibold" style="color: #429a9c">
                      {{ clinic1Name }}
                    </span>
                  </div>
                  <input
                    type="checkbox"
                    :checked="formData.id === 1"
                    @change="updateClinic(1)"
                    class="h-7 w-7 rounded border-2 border-[#429a9c] bg-[#d2d7d7]"
                    style="accent-color: #429a9c;"
                  />
                </div>
              </div>

              <!-- 下部分 - 一段文字 -->
              <div>
                <div
                  class="flex w-[520px] h-[150px] cursor-pointer items-center justify-between bg-[#ececec] p-4 transition-colors hover:bg-[#e3e8e8]"
                >
                  <div class="flex flex-col space-y-2">
                    <span class="text-xl font-semibold" style="color: #429a9c">
                      {{ clinic2Name }}
                    </span>
                  </div>
                  <input
                    type="checkbox"
                    :checked="formData.id === 2"
                    @change="updateClinic(2)"
                    class="h-7 w-7 rounded border-2 border-[#429a9c] bg-[#d2d7d7]"
                    style="accent-color: #429a9c;"
                  />
                </div>
              </div>
            </div>

            <!-- 右侧：按钮 -->
            <div class="flex w-[270px]">

              <button
                @click="validateClinicAndNext"
                :disabled="!formData.id"
                :class="[
                  'rounded-full px-2 py-2 text-white transition-colors w-full h-[46px]',
                  formData.id ? 'bg-[#429a9c] hover:bg-[#429a9c]' : 'bg-gray-400 cursor-not-allowed'
                ]"
              >
              Næste trin
              </button>
            </div>
          </div>
          </div>
        </div>
        
                 <!-- 卡片2 -->
        <div
          v-show="!showTransition && currentCard === 1"
          class="relative rounded-lg mt-8 mb-8"
          style="background-color: #ececec; min-height: 580px; padding: 25px;"
        >
          <div class="rounded-lg bg-white p-6 shadow-lg" style="min-height: 530px">
          <!-- 标题与描述 -->
          <div class="mb-8">
            <h2 class="mb-2 text-2xl font-bold" style="color: #429a9c">Book en tid</h2>
            <p style="color: #444444">Hvordan kan vi hjælpe dig?</p>
          </div>

          <!-- 进度条区域 -->
          <div class="mb-8 flex items-center space-x-25">
            <span class="text-sm font-medium whitespace-nowrap" style="color: #429a9c">Trin 2/6</span>
            <div class="flex-1 h-[10px] overflow-hidden rounded-full bg-gray-200">
              <div
                class="h-full rounded-full"
                style="background-color: #429a9c; width: 33.33%"
              ></div>
            </div>
          </div>

          <!-- 主内容区域 -->
          <div class="flex">
            <!-- 左侧：父子级项目列表 -->
            <div class="overflow-hidden rounded-lg w-[500px]">
              <!-- 父级项目列表 -->
              <div v-for="parentProject in parentProjects" :key="parentProject.id" class="mb-2">
                                <!-- 父级项目 -->
                <div
                  class="flex w-full cursor-pointer items-center justify-between bg-[#ececec] p-4 transition-colors hover:bg-[#e3e8e8]"
                >
                  <div class="flex flex-col space-y-2 flex-1">
                    <div class="flex items-center space-x-2">
                      <span class="text-lg font-semibold" style="color: #429a9c">{{ parentProject.itemname }}</span>
                      <!-- 展开/收起按钮 -->
                      <button 
                        @click.stop="toggleProjectExpansion(parentProject.id)"
                        class="text-[#429a9c] hover:text-[#3a8a8c] transition-colors"
                      >
                        <svg 
                          :class="['w-4 h-4 transform transition-transform', expandedProjects.has(parentProject.id) ? 'rotate-180' : '']"
                          fill="none" 
                          stroke="currentColor" 
                          viewBox="0 0 24 24"
                        >
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                        </svg>
                      </button>
                    </div>
                    <span v-if="parentProject.itemintro" class="text-gray-700 max-w-[300px] font-light text-sm leading-relaxed break-words whitespace-normal">{{ parentProject.itemintro }}</span>
                    <div class="flex items-center space-x-2">
                      <span v-if="parentProject.itemprice && parentProject.itemprice !== 0" class="text-gray-700" style="color: #429a9c">{{ parentProject.itemprice }}</span>
                      <span v-if="parentProject.itemprice && parentProject.itemprice !== 0" class="text-gray-700" style="color: #429a9c">kr</span>
                      <span v-if="parentProject.time_display && parentProject.time_display !== '00:00'" class="text-gray-700 ml-30 font-light">{{ parentProject.time_display }}</span>
                    </div>
                    <span class="text-xs text-gray-500">Mindst 10 sværd for 1000</span>
                  </div>
                  
                  <input
                    type="checkbox"
                    :checked="selectedProjects.has(parentProject.id)"
                    disabled
                    class="h-7 w-7 rounded border-2 border-gray-400 bg-gray-200 cursor-not-allowed"
                    style="accent-color: #429a9c;"
                  />
                </div>
                
                <!-- 子级项目列表 -->
                <div v-if="expandedProjects.has(parentProject.id)" class="ml-6">
                  <div v-for="childProject in getChildProjects(parentProject.id)" :key="childProject.id" class="mt-2">
                    <div
                      class="flex w-full cursor-pointer items-center justify-between bg-[#f5f5f5] p-4 transition-colors hover:bg-[#e8e8e8] border-l-4 border-[#429a9c]"
                    >
                      <div class="flex flex-col space-y-2 flex-1">
                        <span class="text-base font-medium" style="color: #429a9c">{{ childProject.itemname }}</span>
                        <span v-if="childProject.itemintro" class="text-gray-600 max-w-[280px] font-light text-sm leading-relaxed break-words whitespace-normal">{{ childProject.itemintro }}</span>
                        <div class="flex items-center space-x-2">
                          <span v-if="childProject.itemprice && childProject.itemprice !== 0" class="text-gray-600" style="color: #429a9c">{{ childProject.itemprice }}</span>
                          <span v-if="childProject.itemprice && childProject.itemprice !== 0" class="text-gray-600" style="color: #429a9c">kr</span>
                          <span v-if="childProject.time_display && childProject.time_display !== '00:00'" class="text-gray-600 ml-30 font-light text-sm">{{ childProject.time_display }}</span>
                        </div>
                      </div>
                      
                      <!-- 数量输入框 -->
                      <div class="flex flex-col items-center mr-4">
                        <input
                          type="number"
                          v-model="projectCounts[childProject.id]"
                          @input="updateProjectCount(childProject.id)"
                          class="w-16 h-8 px-2 border-2 border-[#429a9c] rounded text-center text-sm no-spinner bg-white focus:border-[#429a9c] focus:outline-none"
                          placeholder="Antal"
                          min="0"
                        />
                      </div>
                      
                      <input
                        type="checkbox"
                        :checked="selectedProjects.has(childProject.id)"
                        @change="toggleProjectSelection(childProject.id)"
                        class="h-6 w-6 rounded border-2 border-[#429a9c] bg-[#d2d7d7]"
                        style="accent-color: #429a9c;"
                      />
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 如果没有项目数据，显示加载状态 -->
              <div v-if="parentProjects.length === 0" class="flex w-full items-center justify-center bg-[#ececec] p-8">
                <span class="text-gray-500">Indlæser...</span>
              </div>
            </div>

            <!-- 右侧：按钮 -->
            <div class="ml-8 flex flex-col items-center w-[270px]">
              <!-- 总价格 -->
              <div class="flex items-center justify-between w-full mb-8">
                <span class="text-xl font-medium" style="color: #429a9c">Subtotal</span>
                <span class="text-xl font-medium" style="color: #429a9c">{{ formData.totalprice || '0' }} kr</span>
              </div>
              <!-- 按钮区域 -->
              <div class="flex flex-col space-y-4 w-full">
                <button
                  @click="validateServiceAndNext"
                  :disabled="selectedProjects.size === 0"
                  :class="[
                    'rounded-full px-2 py-2 text-white transition-colors w-full h-[46px]',
                    selectedProjects.size > 0 ? 'bg-[#429a9c] hover:bg-[#429a9c]' : 'bg-gray-400 cursor-not-allowed'
                  ]"
                >
                Næste trin
                </button>
                <button
                  @click="previousCard"
                  class="rounded-full border-2 border-[#429a9c] px-2 py-2 text-[#429a9c] transition-colors hover:bg-[#429a9c] hover:text-white w-full h-[46px]"
                >
                Tilbage
          </button>
              </div>
            </div>
          </div>
          </div>
        </div>
        
                 <!-- 卡片3 -->
        <div
          v-show="!showTransition && currentCard === 2"
          class="relative rounded-lg mt-8 mb-8"
          style="background-color: #ececec; min-height: 580px; padding: 25px;"
        >
          <div class="rounded-lg bg-white p-6 shadow-lg" style="min-height: 530px">
          <!-- 标题与描述 -->
          <div class="mb-8">
            <h2 class="mb-2 text-2xl font-bold" style="color: #429a9c">Book en tid</h2>
            <p style="color: #444444">Hvornår ønsker du at komme?</p>
          </div>

          <!-- 进度条区域 -->
          <div class="mb-8 flex items-center space-x-25">
            <span class="text-sm font-medium whitespace-nowrap" style="color: #429a9c">Trin 3/6</span>
            <div class="flex-1 h-[10px] overflow-hidden rounded-full bg-gray-200">
              <div class="h-full rounded-full" style="background-color: #429a9c; width: 50%"></div>
            </div>
          </div>

          <!-- 主内容区域 -->
          <div class="flex h-full space-x-8">
            <!-- 左部分：日期选择器 -->
            <div class="w-1/3">
              <div class="bg-[#ececec] rounded-lg p-6 shadow-sm">
                <!-- 自定义日期选择器 -->
                <div class="custom-calendar">
                  <div class="calendar-header">
                    <button @click="previousMonth" class="month-nav-btn">&lt;</button>
                    <span class="current-month">{{ currentMonthYear }}</span>
                    <button @click="nextMonth" class="month-nav-btn">&gt;</button>
                  </div>
                  
                  <div class="calendar-weekdays">
                    <div class="weekday">M</div>
                    <div class="weekday">T</div>
                    <div class="weekday">O</div>
                    <div class="weekday">T</div>
                    <div class="weekday">F</div>
                    <div class="weekday">L</div>
                    <div class="weekday">S</div>
                  </div>
                  
                  <div class="calendar-days">
                    <div 
                      v-for="day in calendarDays" 
                      :key="day.date"
                      @click="selectDate(day.date)"
                      :class="[
                        'calendar-day',
                        day.isCurrentMonth ? 'current-month' : 'other-month',
                        day.isSelected ? 'selected' : '',
                        day.isToday ? 'today' : '',
                        day.isAvailable ? '' : 'unavailable',
                        day.isPastDate ? 'past-date' : ''
                      ]"
                    >
                      {{ day.dayNumber }}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 中间部分：日期时间和时间选择 -->
            <div class="w-1/3">
              <!-- 上部分：完整日期时间 -->
              <div class="mb-6">
                <div class="text-lg font-medium text-gray-700">
                  {{ formatSelectedDate(selectedDate) }} | {{ selectedTime }}
                </div>
              </div>
              
               <!-- 下部分：时间按钮 -->
               <div class="mb-2">
                 
               </div>
               <div class="grid grid-cols-3 gap-2 h-40 overflow-y-auto bg-[#ececec] p-4 rounded-lg">
                 <button 
                   v-for="time in availableTimes"
                   :key="time"
                   @click="selectTime(time)"
                   :class="[
                     'h-10 px-2 rounded-lg font-medium text-sm transition-colors',
                     selectedTime === time 
                       ? 'bg-[#429a9c] text-white' 
                       : 'bg-white border-2 border-[#429a9c] text-gray-700 hover:bg-gray-50'
                   ]"
                 >
                   {{ time }}
                 </button>
               </div>
            </div>

            <!-- 右部分：两个按钮 -->
            <div class="w-1/3 flex flex-col space-y-4">
              <button
                @click="nextCard"
                :disabled="!selectedTime || availableTimes.length === 0"
                :class="[
                  'w-full py-3 px-6 rounded-full font-medium transition-colors',
                  selectedTime && availableTimes.length > 0
                    ? 'bg-[#429a9c] text-white hover:bg-[#429a9c]' 
                    : 'bg-gray-400 text-gray-600 cursor-not-allowed'
                ]"
              >
                Næste trin
              </button>
              <button
                @click="() => showTransitionAnimation(2, 1)"
                class="w-full py-3 px-6 bg-white border-2 border-[#429a9c] text-gray-700 rounded-full font-medium hover:bg-gray-50 transition-colors"
              >
                Tilbage
          </button>
            </div>
          </div>
          </div>
        </div>
        
                 <!-- 卡片4 -->
        <div
          v-show="!showTransition && currentCard === 3"
          class="relative rounded-lg mt-8 mb-8"
          style="background-color: #ececec; min-height: 580px; padding: 25px;"
        >
          <div class="rounded-lg bg-white p-6 shadow-lg" style="min-height: 530px">
          <!-- 标题与描述 -->
          <div class="mb-8">
            <h2 class="mb-2 text-2xl font-bold" style="color: #429a9c">Book en tid</h2>
            <p style="color: #444444">Kundeoplysninger</p>
          </div>

          <!-- 进度条区域 -->
          <div class="mb-8 flex items-center space-x-25">
            <span class="text-sm font-medium whitespace-nowrap" style="color: #429a9c">Trin 4/6</span>
            <div class="flex-1 h-[10px] overflow-hidden rounded-full bg-gray-200">
              <div
                class="h-full rounded-full"
                style="background-color: #429a9c; width: 66.67%"
              ></div>
            </div>
          </div>

          <!-- 主内容区域 -->
          <div class="flex h-full space-x-8">
            <!-- 左部分：表单 -->
            <div class="flex-1">
              <form class="space-y-6">
                                <!-- 第一行：姓名 -->
                <div class="grid grid-cols-2 gap-4">
                  <div>
                    <label class="block text-sm font-medium mb-2" style="color: #429a9c">Fornavn *</label>
                    <input 
                      type="text" 
                      v-model="formData.firstname"
                      @blur="validateFirstname"
                      :class="[
                        'w-full px-4 py-3 border-2 rounded-lg bg-white focus:outline-none transition-colors',
                        firstnameError ? 'border-red-500' : 'border-[#429a9c] focus:border-[#429a9c]'
                      ]"
                      :placeholder="firstnameError || ''"
                    />
                  </div>
                  <div>
                    <label class="block text-sm font-medium mb-2" style="color: #429a9c">Efternavn</label>
                    <input 
                      type="text" 
                      v-model="formData.lastname"
                      class="w-full px-4 py-3 border-2 border-[#429a9c] rounded-lg bg-white focus:outline-none focus:border-[#429a9c] transition-colors"
                    />
                  </div>
                </div>

                <!-- 第二行：邮箱和电话 -->
                <div class="grid grid-cols-2 gap-4">
                  <div>
                    <label class="block text-sm font-medium mb-2" style="color: #429a9c">E-mail *</label>
                    <input 
                      type="email" 
                      v-model="formData.email"
                      @blur="validateEmail"
                      title="Indtast en gyldig e-mail adresse (f.eks. navn@domæne.dk)"
                      :class="[
                        'w-full px-4 py-3 border-2 rounded-lg bg-white focus:outline-none transition-colors',
                        emailError ? 'border-red-500' : 'border-[#429a9c] focus:border-[#429a9c]'
                      ]"
                      :placeholder="emailError || ''"
                    />
                  </div>
                  <div>
                    <label class="block text-sm font-medium mb-2" style="color: #429a9c">Mobil telefon</label>
                    <input 
                      type="tel" 
                      v-model="formData.phone"
                      class="w-full px-4 py-3 border-2 border-[#429a9c] rounded-lg bg-white focus:outline-none focus:border-[#429a9c] transition-colors"
                    />
              </div>
            </div>

                <!-- 第三行：地址 -->
                <div>
                  <label class="block text-sm font-medium mb-2" style="color: #429a9c">Adresse</label>
                  <input 
                    type="text" 
                    v-model="formData.address"
                    class="w-full px-4 py-3 border-2 border-[#429a9c] rounded-lg bg-white focus:outline-none focus:border-[#429a9c] transition-colors"
                  />
                </div>
              </form>
            </div>

            <!-- 右部分：两个按钮 -->
            <div class="w-[270px] flex flex-col space-y-4">
              <button
                @click="validateAndNext"
                class="w-full py-3 px-6 bg-[#429a9c] text-white rounded-full font-medium hover:bg-[#429a9c] transition-colors"
              >
                Næste trin
              </button>
              <button
                @click="() => showTransitionAnimation(3, 2)"
                class="w-full py-3 px-6 bg-white border-2 border-[#429a9c] text-gray-700 rounded-full font-medium hover:bg-gray-50 transition-colors"
              >
                Tilbage
          </button>
            </div>
          </div>
          </div>
        </div>
        
                 <!-- 卡片5 -->
        <div
          v-show="!showTransition && currentCard === 4"
          class="relative rounded-lg mt-8 mb-8"
          style="background-color: #ececec; min-height: 900px; padding: 25px;"
        >
          <div class="rounded-lg bg-white p-6 shadow-lg" style="min-height: 850px">
          <!-- 标题与描述 -->
          <div class="mb-8">
            <h2 class="mb-2 text-2xl font-bold" style="color: #429a9c">Book en tid</h2>
            <p style="color: #444444">Booking oversigt</p>
          </div>

          <!-- 进度条区域 -->
          <div class="mb-8 flex items-center space-x-25">
            <span class="text-sm font-medium whitespace-nowrap" style="color: #429a9c">Trin 5/6</span>
            <div class="flex-1 h-[10px] overflow-hidden rounded-full bg-gray-200">
              <div
                class="h-full rounded-full"
                style="background-color: #429a9c; width: 83.33%"
              ></div>
            </div>
          </div>

          <!-- 问候语 -->
          <div class="mb-8">
            <h2 class="text-1xl" style="color: #444444">Kære {{ formData.firstname }} {{ formData.lastname }}</h2>
            <p style="color: #444444">du bedes gennemgå og bekræfte detaljerne for din reservation:</p>
          </div>

          <!-- 主内容区域 -->
          <div class="flex space-x-8">
            <!-- 左边区域 - 预订摘要 -->
            <div class="w-[520px] h-auto rounded-lg">
              <!-- 预订摘要卡片 -->
              <div class="bg-[#ececec] rounded-lg p-6 shadow-sm">
                <!-- 区域1：标题 -->

                <div>
                  <div class="text-base font-semibold text-gray-800 mb-1">
                    {{ formData.clinicname }}
                  </div>
                  <div class="border-t-2 border-gray-300 mb-2"></div>
                  <div class="text-sm text-gray-500 mb-6">Booket klinik</div>
                </div>

                <div>
                  <div class="text-base font-semibold text-gray-800 mb-1">
                    {{ formData.date || formatSelectedDate(selectedDate) }} / {{ formData.time || selectedTime }}
                  </div>
                </div>
                
                <!-- 第一个分割线 -->
                <div class="border-t-2 border-gray-300 mb-2"></div>
                <div class="text-sm text-gray-500 mb-6">Dato og tid booket</div>
                
                <!-- 区域2：项目与价格 -->
                <div class="mb-2">
                  <!-- 显示选中的项目数据 -->
                  <div v-for="parentProject in parentProjects" :key="parentProject.id">
                    <!-- 检查父级项目是否有选中的子级项目 -->
                    <div v-if="selectedProjects.has(parentProject.id)">
                      <!-- 父级项目 -->
                      <div class="flex justify-start items-center mb-2">
                        <span v-if="parentProject.itemprice && parentProject.itemprice !== 0" class="text-base font-medium text-gray-800 ml-4 mr-8 w-20">
                          {{ parentProject.itemprice }} kr
                        </span>
                        <span 
                          class="text-xl font-bold text-gray-800"
                          :style="parentProject.itemprice === 0 ? 'margin-left: 1rem;' : ''"
                        >
                          {{ parentProject.itemname }}
                        </span>
                      </div>
                      
                      <!-- 子级项目 -->
                      <div v-for="childProject in getChildProjects(parentProject.id)" :key="childProject.id" class="ml-6">
                        <div v-if="selectedProjects.has(childProject.id)" class="flex justify-start items-center mb-3">
                          <span v-if="childProject.itemprice && childProject.itemprice !== 0" class="text-base font-medium text-gray-800 ml-4 mr-8 w-20">
                            {{ childProject.itemprice }} kr
                          </span>
                          <span 
                            class="text-lg font-medium text-gray-800"
                            :style="childProject.itemprice === 0 ? 'margin-left: 1rem;' : ''"
                          >
                            {{ childProject.itemname }}
                            <span v-if="projectCounts[childProject.id] && projectCounts[childProject.id] > 1" class="text-gray-600 font-normal">
                              × {{ projectCounts[childProject.id] }}
                            </span>
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 第二个分割线 -->
                <div class="border-t-2 border-gray-300 mb-2"></div>
                <div class="text-sm text-gray-500 mb-6">Tjenester og assistenter</div>
                
                <!-- 区域3：总价 -->
                <div class="mb-2">
                  <div class="text-1xl font-bold text-gray-800 mb-1">{{ formData.totalprice || '0' }} kr</div>
                </div>
                
                <!-- 第三个分割线 -->
                <div class="border-t-2 border-gray-300 mb-2"></div>
                <div class="text-sm text-gray-500">Total beløb</div>
              </div>
              
              <!-- 留言区域 -->
              <div class="mt-6">
                <div class="flex items-center space-x-3">
                  <label class="text-sm font-bold text-black whitespace-nowrap flex flex-col">
                    <span>Læg en</span>
                    <span>besked.</span>
                  </label>
                  <textarea 
                    v-model="formData.message"
                    class="flex-1 border-2 border-[#429a9c] rounded-lg p-3 resize-none"
                    rows="4"
                    placeholder="Læg en besked"
                  ></textarea>
                </div>
              </div>
                
                <!-- 内容显示区域 -->
                <div class="mt-10">
                  <!-- 主标题 -->
                  <div class="mb-3 ml-6">
                    <h3 class="text-lg mb-2" style="color: #429a9c">Gennemfør din reservation</h3>
                    <p class="text-sm" style="color: #429a9c">Klik på Gennemfør booking</p>
                  </div>
                  
                  <!-- 条款和条件框 -->
                  <div class="bg-[#ececec] rounded-md p-6 mt-6">
                    <h4 class="text-xs font-bold mb-2" style="color: #6e6e6e">Vilkår og betingelser</h4>
                    <p class="text-xs" style="color: #6e6e6e">
                      I tilfælde af forsinkelse beholder vi din "plads" i 15 minutter, derefter mister du din prioritet.
                    </p>
                  </div>
                </div>
              </div>

            <!-- 右边区域 - 包含按钮 -->
            <div class="flex flex-col items-center flex-1">
              <button
                @click="subscribeBooking"
                :disabled="!selectedTime || availableTimes.length === 0"
                :class="[
                  'w-full py-3 px-6 mb-4 rounded-full font-medium transition-colors' ,
                  selectedTime && availableTimes.length > 0
                    ? 'bg-[#429a9c] text-white hover:bg-[#429a9c]' 
                    : 'bg-gray-400 text-gray-600 cursor-not-allowed'
                ]"
                data-booking-button
              >
              Gennemfør booking
              </button>
              <button
                @click="() => showTransitionAnimation(4, 3)"
                class="w-full py-3 px-6 bg-white border-2 border-[#429a9c] text-gray-700 rounded-full font-medium hover:bg-gray-50 transition-colors"
              >
                Start forfra
              </button>
            </div>
          </div>
        </div>
      </div>

        <!-- 卡片6 -->
        <div
          v-show="!showTransition && currentCard === 5"
          class="relative rounded-lg mt-8 mb-8"
          style="background-color: #ececec; min-height: 580px; padding: 25px;"
        >
          <div class="rounded-lg bg-white p-6 shadow-lg" style="min-height: 530px">
          <!-- 标题与描述 -->
          <div class="mb-8">
            <h2 class="mb-2 text-2xl font-bold" style="color: #429a9c">Book en tid</h2>
            <p style="color: #444444">Booking Bekreftelse</p>
          </div>

          <!-- 进度条区域 -->
          <div class="mb-8 flex items-center space-x-25">
            <span class="text-sm font-medium whitespace-nowrap" style="color: #429a9c">Trin 6/6</span>
            <div class="flex-1 h-[10px] overflow-hidden rounded-full bg-gray-200">
              <div
                class="h-full rounded-full"
                style="background-color: #429a9c; width: 100%"
              ></div>
            </div>
          </div>

          <!-- 标题和图标 -->
          <div class="flex items-center mb-6">
                 <div class="w-12 h-12 rounded-full flex items-center justify-center mr-4"
                      :class="bookingResult?.code === 1 ? 'bg-green-500' : 'bg-red-500'">
                   <svg v-if="bookingResult?.code === 1" class="w-8 h-8 text-white" fill="currentColor" viewBox="0 0 20 20">
                     <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
                   </svg>
                   <svg v-else class="w-8 h-8 text-white" fill="currentColor" viewBox="0 0 20 20">
                     <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"/>
                   </svg>
                 </div>
                 <h2 class="text-2xl font-bold"
                     :class="bookingResult?.code === 1 ? 'text-green-600' : 'text-red-600'">
                   {{ bookingResult?.code === 1 ? 'Din booking er gennemført' : 'Din aftale mislykkedes' }}
                 </h2>
               </div>
               
               <!-- 预订号码 - 只在成功时显示 -->
               <div v-if="bookingResult?.code === 1" class="mb-6">
                 <div class="text-sm text-gray-600 mb-2">Booking nummer</div>
                 <div class="text-4xl font-bold text-gray-800">{{ bookingResult.id }}</div>
               </div>
               
               <!-- 说明文字 -->
               <div class="mb-6 text-gray-700 leading-relaxed">
                 <div v-if="bookingResult?.code === 1">
                   Du vil modtage en bookingbekræftelse via e-mail. Hvis du ikke modtager en e-mail inden for 5 minutter, skal du tjekke din uønskede post eller spammappe. Hvis du har brug for at ændre din reservation, bedes du ringe til <span class="font-bold">55608880</span> eller sende en e-mail til <span class="font-bold">info@zenix.nu</span>.
                 </div>
                 <div v-else>
                   Der opstod en fejl under din reservation. Prøv venligst igen eller kontakt os på <span class="font-bold">55608880</span> eller send en e-mail til <span class="font-bold">info@zenix.nu</span>.
                 </div>
               </div>
               
               <!-- 倒计时重定向 - 无论成功还是失败都显示 -->
               <div class="text-gray-700">
                 Du bliver omdirigeret om <span class="font-semibold">{{ countdown }}</span> sekunder
               </div>
            </div>
          </div>
          </div>
        </div>

</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { getAllClinicInfo, getClinicInfo, getItemInfo, subscribe } from "../api/behandlinger";

// 诊所数据类型定义
interface Clinic {
  id: number;
  clinicname: string;
  week: string;
  time: string;
  address: string;
  opentime: string;
  week_text: string;
  time_text: string;
  opentime_text: string;
  create_time_text: string;
  update_time_text: string;
}

// 项目数据类型定义
interface Item {
  id: number;
  itemname: string;
  itemintro: string | null;
  itemprice: string;
  itemtime: string;
  clinicid: number;
}

// 新的父子级项目数据类型定义
interface ProjectItem {
  id: number;
  itemname: string;
  itemintro: string;
  itemprice: number;
  itemtime: string;
  grade: string;
  gradeid: number;
  clinicid: number;
  clinic_name: string;
  title: string;
  pid: number;
  name: string;
  type: string;
  price_display: string;
  time_display: string;
}

interface SubscribeResponse {
  code: number;
  msg: string;
  data: any;
}

// 表单数据
const formData = ref({
  id: 0,
  clinicname: '',
  itemids: [] as {id: number, count: number}[], // 修改：存储选中的项目ID和数量，格式为[{id:1, count:10}, {id:2, count:10}]数组
  totalprice: '',
  date: '',
  time: '',
  firstname: '',
  lastname: '',
  email: '',
  phone: '',
  address: '',
  message: '',
});

// 存储所有诊所信息
const allClinics = ref<Clinic[]>([]);

// 这个变量不再需要，因为现在使用projectItems

// 存储新的父子级项目信息
const projectItems = ref<ProjectItem[]>([]);

// 存储诊所信息
const clinicInfo = ref<Clinic | null>(null);

// 存储预约结果
const bookingResult = ref<any>(null);

// 路由实例
const router = useRouter();

// 倒计时相关
const countdown = ref(15);
const countdownTimer = ref<number | null>(null);

// 计算属性：获取诊所名称
const clinic1Name = computed(() => {
  const clinic = allClinics.value.find(c => c.id === 1);
  return clinic ? clinic.clinicname : 'Indlæser...';
});

const clinic2Name = computed(() => {
  const clinic = allClinics.value.find(c => c.id === 2);
  return clinic ? clinic.clinicname : 'Indlæser...';
});

// 这些计算属性不再需要，因为现在使用动态的项目选择

// 计算属性：获取父级项目
const parentProjects = computed(() => {
  return projectItems.value.filter(item => item.grade === 'parent');
});

// 计算属性：获取子级项目
const getChildProjects = (parentId: number) => {
  return projectItems.value.filter(item => item.pid === parentId);
};

// 计算属性：获取诊所可用的时间
const availableTimes = computed(() => {
  if (!clinicInfo.value?.time) return ['10:30', '11:15', '12:00', '13:30', '14:15', '15:00', '15:45'];
  
  const allTimes = clinicInfo.value.time.split(',').map(t => t.trim());
  
  // 如果没有选择日期，返回所有时间
  if (!selectedDate.value) return allTimes;
  
  const now = new Date();
  const selectedDateOnly = new Date(selectedDate.value.getFullYear(), selectedDate.value.getMonth(), selectedDate.value.getDate());
  const todayOnly = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  
  // 如果选择的是今天，需要过滤掉已经过去的时间
  if (selectedDateOnly.getTime() === todayOnly.getTime()) {
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();
    
    return allTimes.filter(time => {
      const [hour, minute] = time.split(':').map(Number);
      
      // 如果时间比当前时间早，则不可预约
      if (hour < currentHour) return false;
      if (hour === currentHour && minute <= currentMinute) return false;
      
      return true;
    });
  }
  
  // 如果不是今天，返回所有时间
  return allTimes;
});

// 计算属性：获取诊所可用的星期
const availableWeeks = computed(() => {
  if (!clinicInfo.value?.week) return [1, 2, 3, 4, 5, 6, 0]; // 默认所有星期都可选
  return clinicInfo.value.week.split(',').map(w => parseInt(w.trim()));
});

// 获取所有诊所信息
const fetchAllClinics = async () => {
  try {
    const response = await getAllClinicInfo();
    allClinics.value = response.data || [];
    console.log('所有诊所信息:', allClinics.value);
  } catch (error) {
    console.error('获取所有诊所信息失败:', error);
  }
};

// 初始化表单数据
const initializeFormData = () => {
  // 设置默认日期和时间
  const today = new Date();
  const weekdays = ['søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'];
  const months = ['januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december'];
  
  const weekday = weekdays[today.getDay()];
  const day = today.getDate();
  const month = months[today.getMonth()];
  const year = today.getFullYear();
  
  formData.value.date = `${weekday} den ${day}. ${month} ${year}`;
  formData.value.time = defaultTime.value;
};

// 组件挂载时获取所有诊所信息
onMounted(() => {
  fetchAllClinics();
  initializeFormData();
});

// 组件卸载时清理定时器
onUnmounted(() => {
  clearCountdown();
});

// 当前显示的卡片索引
const currentCard = ref(0);

// 选中的日期
const selectedDate = ref<Date>(new Date()); // 默认选中今天

// 选中的时间
const selectedTime = ref<string>('10:30'); // 默认选中第一个时间段

// 计算属性：获取默认时间
const defaultTime = computed(() => {
  return availableTimes.value.length > 0 ? availableTimes.value[0] : '10:30';
});



// 展开的项目ID集合
const expandedProjects = ref<Set<number>>(new Set());

// 选中的项目ID集合
const selectedProjects = ref<Set<number>>(new Set());

// 项目数量映射
const projectCounts = ref<Record<number, number>>({});

// 表单验证错误状态
const firstnameError = ref<string>('');
const emailError = ref<string>('');

// 当前显示的月份
const currentMonth = ref(new Date());

// 格式化选中日期的函数
const formatSelectedDate = (date: Date): string => {
  if (!date) return '';
  
  const weekdays = ['søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'];
  const months = ['januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december'];
  
  const weekday = weekdays[date.getDay()];
  const day = date.getDate();
  const month = months[date.getMonth()];
  const year = date.getFullYear();
  
  return `${weekday} den ${day}. ${month} ${year}`;
};

// 将日期转换为YYYY-MM-DD格式
const formatDateForAPI = (date: Date): string => {
  if (!date) return '';
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  return `${year}-${month}-${day}`;
};

// 计算当前月份和年份显示
const currentMonthYear = computed(() => {
  const month = currentMonth.value.getMonth();
  const year = currentMonth.value.getFullYear();
  const months = ['januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december'];
  return `${months[month]} ${year}`;
});

// 计算日历天数
const calendarDays = computed(() => {
  const year = currentMonth.value.getFullYear();
  const month = currentMonth.value.getMonth();
  
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const startDate = new Date(firstDay);
  startDate.setDate(startDate.getDate() - firstDay.getDay() + 1); // 从周一开始
  
  const days = [];
  const today = new Date();
  const todayOnly = new Date(today.getFullYear(), today.getMonth(), today.getDate());
  
  for (let i = 0; i < 42; i++) {
    const date = new Date(startDate);
    date.setDate(startDate.getDate() + i);
    
    // 检查这个日期是否可选（星期是否在诊所开放时间内）
    const dayOfWeek = date.getDay(); // 0=周日, 1=周一, 2=周二, 3=周三, 4=周四, 5=周五, 6=周六
    const isAvailable = availableWeeks.value.includes(dayOfWeek);
    
    // 检查日期是否为今天或以后
    const dateOnly = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    const isPastDate = dateOnly < todayOnly;
    
    days.push({
      date: date,
      dayNumber: date.getDate(),
      isCurrentMonth: date.getMonth() === month,
      isSelected: date.toDateString() === selectedDate.value.toDateString(),
      isToday: date.toDateString() === today.toDateString(),
      isAvailable: isAvailable && !isPastDate, // 只有非过去日期且星期可用的日期才可选
      isPastDate: isPastDate // 新增：标记是否为过去日期
    });
  }
  
  return days;
});

// 上个月
const previousMonth = () => {
  currentMonth.value = new Date(currentMonth.value.getFullYear(), currentMonth.value.getMonth() - 1, 1);
};

// 下个月
const nextMonth = () => {
  currentMonth.value = new Date(currentMonth.value.getFullYear(), currentMonth.value.getMonth() + 1, 1);
};

// 更新itemids字段
const updateItemIds = () => {
  const selectedItems = Array.from(selectedProjects.value).map(projectId => ({
    id: projectId,
    count: projectCounts.value[projectId] || 0
  }));
  formData.value.itemids = selectedItems;
};

// 切换项目展开状态
const toggleProjectExpansion = (projectId: number) => {
  if (expandedProjects.value.has(projectId)) {
    expandedProjects.value.delete(projectId);
  } else {
    expandedProjects.value.add(projectId);
  }
};

// 切换项目选择状态
const toggleProjectSelection = (projectId: number) => {
  const project = projectItems.value.find(item => item.id === projectId);
  if (!project) return;
  
  // 如果是父级项目，不允许直接操作
  if (project.grade === 'parent') {
    return;
  }
  
  if (selectedProjects.value.has(projectId)) {
    // 取消选择子级项目
    selectedProjects.value.delete(projectId);
    projectCounts.value[projectId] = 0;
  } else {
    // 选择子级项目
    selectedProjects.value.add(projectId);
    if (!projectCounts.value[projectId]) {
      projectCounts.value[projectId] = 1;
    }
  }
  
  // 更新父级项目的选择状态
  const parentProject = projectItems.value.find(item => item.id === project.pid);
  if (parentProject) {
    const allChildProjects = getChildProjects(parentProject.id);
    const selectedChildProjects = allChildProjects.filter(child => selectedProjects.value.has(child.id));
    
    // 如果有任何子级项目被选中，就选中父级项目
    if (selectedChildProjects.length > 0) {
      selectedProjects.value.add(parentProject.id);
    } else {
      // 如果没有子级项目被选中，就取消选择父级项目
      selectedProjects.value.delete(parentProject.id);
    }
  }
  
  calculateTotalPriceFromProjects();
  updateItemIds(); // 更新itemids字段
};

// 根据选中的项目计算总价格
const calculateTotalPriceFromProjects = () => {
  let total = 0;
  selectedProjects.value.forEach(projectId => {
    const project = projectItems.value.find(item => item.id === projectId);
    if (project) {
      const count = projectCounts.value[projectId] || 0;
      const basePrice = project.itemprice;
      
      if (count > 0) {
        // 如果数量大于等于10，总价 = 原价 × 数量 - 1000
        if (count >= 10) {
          const subtotal = basePrice * count;
          const discount = 1000;
          const discountedTotal = subtotal - discount;
          const minTotal = subtotal * 0.1; // 最低总价为原总价的10%
          total += Math.max(minTotal, discountedTotal);
        } else {
          // 如果数量小于10，总价 = 原价 × 数量
          total += basePrice * count;
        }
      }
    }
  });
  formData.value.totalprice = total.toString();
};

// 计算总价格
const calculateTotalPrice = () => {
  let total = 0;
  selectedProjects.value.forEach(projectId => {
    const project = projectItems.value.find(item => item.id === projectId);
    if (project) {
      total += project.itemprice;
    }
  });
  formData.value.totalprice = total.toString();
};

// 更新诊所选择（只能选择一个）
const updateClinic = (clinicId: number) => {
  if (formData.value.id === clinicId) {
    // 如果点击的是已选中的诊所，则取消选择
    formData.value.id = 0;
    formData.value.clinicname = '';
  } else {
    // 否则选择新的诊所
    formData.value.id = clinicId;
    // 根据诊所ID设置诊所名称
    if (clinicId === 1) {
      formData.value.clinicname = clinic1Name.value;
    } else if (clinicId === 2) {
      formData.value.clinicname = clinic2Name.value;
    }
  }
};

// 验证姓名字段
const validateFirstname = () => {
  if (!formData.value.firstname.trim()) {
    firstnameError.value = 'Fornavn er påkrævet';
  } else {
    firstnameError.value = '';
  }
};

// 验证邮箱字段
const validateEmail = () => {
  const email = formData.value.email.trim();
  if (!email) {
    emailError.value = 'E-mail er påkrævet';
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    emailError.value = 'Indtast en gyldig e-mail';
  } else {
    emailError.value = '';
  }
};

// 验证并进入下一张卡片
const validateAndNext = () => {
  // 验证必填字段
  validateFirstname();
  validateEmail();
  
  // 如果没有错误，则进入下一张卡片
  if (!firstnameError.value && !emailError.value) {
    nextCard();
  }
};

// 验证诊所选择并进入下一张卡片
const validateClinicAndNext = async () => {
  if (formData.value.id) {
    try {
      // 调用第一个接口：获取诊所信息
      const clinicResponse = await getClinicInfo(formData.value.id);
      console.log('诊所信息:', clinicResponse);
      clinicInfo.value = clinicResponse.data; // 存储诊所信息
      
      // 更新选中的时间为诊所的第一个可用时间
      if (availableTimes.value.length > 0) {
        selectedTime.value = availableTimes.value[0];
        formData.value.time = availableTimes.value[0];
      }
      
      // 调用第二个接口：获取项目信息
      const itemsResponse = await getItemInfo(formData.value.id);
      console.log('项目信息:', itemsResponse);
      
      // 不再需要存储到items变量，直接使用projectItems
      
      // 将新的父子级项目信息存储到projectItems变量中
      if (itemsResponse.data && Array.isArray(itemsResponse.data)) {
        projectItems.value = itemsResponse.data;
      }
      
      // 如果两个接口都调用成功，则进入下一张卡片
      nextCard();
    } catch (error) {
      console.error('获取数据失败:', error);
      // 这里可以添加错误处理，比如显示错误提示
      // 暂时仍然允许进入下一张卡片
      nextCard();
    }
  }
};

// 验证服务选择并进入下一张卡片
const validateServiceAndNext = () => {
  if (selectedProjects.value.size > 0) {
    nextCard();
  }
};

// 更新项目数量
const updateProjectCount = (projectId: number) => {
  const count = projectCounts.value[projectId] || 0;
  if (count > 0) {
    selectedProjects.value.add(projectId);
  } else {
    selectedProjects.value.delete(projectId);
  }
  calculateTotalPriceFromProjects();
  updateItemIds();
};



// 选择日期
const selectDate = (date: Date) => {
  // 检查这个日期是否为过去日期
  const today = new Date();
  const todayOnly = new Date(today.getFullYear(), today.getMonth(), today.getDate());
  const dateOnly = new Date(date.getFullYear(), date.getMonth(), date.getDate());
  
  if (dateOnly < todayOnly) {
    return; // 如果是过去日期，直接返回，不允许选择
  }
  
  // 检查这个日期是否可选（星期是否在诊所开放时间内）
  const dayOfWeek = date.getDay();
  if (!availableWeeks.value.includes(dayOfWeek)) {
    return; // 如果日期不可选，直接返回
  }
  
  selectedDate.value = date;
  formData.value.date = formatSelectedDate(date);
  
  // 更新选中的时间为第一个可用的时间
  if (availableTimes.value.length > 0) {
    selectedTime.value = availableTimes.value[0];
    formData.value.time = availableTimes.value[0];
  }
};

// 选择时间的函数
const selectTime = (time: string): void => {
  selectedTime.value = time;
  formData.value.time = time;
};

// 过场动画相关
const showTransition = ref(false);
const transitionProgress = ref(0);
let transitionTimer: number | null = null;

// 显示过场动画
const showTransitionAnimation = (fromCard: number, toCard: number) => {
  showTransition.value = true;
  transitionProgress.value = 0; // 从0开始
  
  // 清除之前的定时器
  if (transitionTimer) {
    clearInterval(transitionTimer);
  }
  
  // 创建简单的从左到右移动动画
  const duration = 800; // 0.8秒动画
  const interval = 20; // 每20ms更新一次
  const steps = duration / interval;
  
  let currentStep = 0;
  
  transitionTimer = setInterval(() => {
    currentStep++;
    // 从0移动到80，让短线段从最左边移动到最右边
    transitionProgress.value = (currentStep / steps) * 80;
    
    if (currentStep >= steps) {
      // 动画完成，跳转到目标卡片
      showTransition.value = false;
      currentCard.value = toCard;
      clearInterval(transitionTimer!);
      transitionTimer = null;
    }
  }, interval);
};

// 切换到下一张卡片
const nextCard = (): void => {
  const fromCard = currentCard.value;
  const toCard = (currentCard.value + 1) % 6;
  showTransitionAnimation(fromCard, toCard);
};

// 切换到上一张卡片
const previousCard = (): void => {
  const fromCard = currentCard.value;
  const toCard = currentCard.value === 0 ? 5 : currentCard.value - 1;
  showTransitionAnimation(fromCard, toCard);
};

// 预约接口调用
const subscribeBooking = async () => {
  try {
    // 显示加载状态
    const button = document.querySelector('[data-booking-button]') as HTMLButtonElement;
    if (button) {
      button.disabled = true;
      button.textContent = 'Booker...';
    }
    
    // 准备数据发送到后端
    const bookingData = {
      ...formData.value,
      date: formatDateForAPI(selectedDate.value), // 使用格式化后的日期
      time: selectedTime.value,
      // itemids字段已经通过updateItemIds()函数更新为[1,2,3,4]格式的数组
    };

    

    const response = await subscribe(bookingData) as unknown as SubscribeResponse;
    console.log('预约响应:', response);
    
    if (response.code === 1) {
      // 预约成功，存储预约结果
      bookingResult.value = {
        ...response.data,
        code: response.code,
        msg: response.msg
      };
      console.log('预约成功:', response.msg);
    } else {
      // 预约失败，存储错误信息
      const errorMsg = response?.msg || 'Booking mislykkedes';
      console.error('预约失败:', errorMsg);
      bookingResult.value = {
        code: response?.code || 0,
        msg: errorMsg
      };
    }
    
    // 无论成功与否，都跳转到第六张卡片显示结果
    showTransitionAnimation(4, 5);
    
    // 无论成功还是失败，都启动倒计时
    startCountdown();
  } catch (error) {
    console.error('预约失败:', error);
    // 网络错误等情况，也跳转到第六张卡片显示错误
    bookingResult.value = {
      code: 0,
      msg: 'Booking mislykkedes, prøv venligst igen senere'
    };
    showTransitionAnimation(4, 5);
    // 网络错误时也启动倒计时
    startCountdown();
  } finally {
    // 恢复按钮状态
    const button = document.querySelector('[data-booking-button]') as HTMLButtonElement;
    if (button) {
      button.disabled = false;
      button.textContent = 'Gennemfør booking';
    }
  }
};

// 启动倒计时
const startCountdown = () => {
  // 重置倒计时
  countdown.value = 15;
  
  // 清除之前的定时器
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
  
  // 启动新的倒计时
  countdownTimer.value = setInterval(() => {
    countdown.value--;
    
    if (countdown.value <= 0) {
      // 倒计时结束，清空表单并跳转到forside页面
      clearCountdown();
      resetForm();
      router.push('/');
    }
  }, 1000);
};

// 清除倒计时
const clearCountdown = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
    countdownTimer.value = null;
  }
};

// 重置表单数据
const resetForm = () => {
  // 重置表单数据
  formData.value = {
    id: 0,
    clinicname: '',
    itemids: [], // 修改：存储选中的项目ID和数量，格式为[{id:1, count:10}, {id:2, count:10}]数组
    totalprice: '',
    date: '',
    time: '',
    firstname: '',
    lastname: '',
    email: '',
    phone: '',
    address: '',
    message: '',
  };
  
  // 重置其他相关状态
  selectedDate.value = new Date();
  selectedTime.value = '';
  currentCard.value = 0;
  
  // 清除错误信息
  firstnameError.value = '';
  emailError.value = '';
  
  // 清除预约结果
  bookingResult.value = null;
  
  // 清除新的父子级项目状态
  expandedProjects.value.clear();
  selectedProjects.value.clear();
  projectItems.value = [];
  projectCounts.value = {};
};
</script>

<style scoped>
/* 治疗页面特定样式 */

/* 自定义日历样式 */
.custom-calendar {
  width: 100%;
  font-family: inherit;
}

.calendar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.month-nav-btn {
  background: #429a9c;
  color: white;
  border: none;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s;
}

.month-nav-btn:hover {
  background: #3a8a8c;
}

.current-month {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 2px;
  margin-bottom: 6px;
}

.weekday {
  text-align: center;
  font-size: 12px;
  font-weight: 500;
  color: #6b7280;
  padding: 8px 0;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 2px;
}

.calendar-day {
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
  min-height: 24px;
}

.calendar-day.current-month {
  color: #374151;
  background-color: #ffffff;
}

.calendar-day.other-month {
  color: #9ca3af;
  background-color: #ececec;
}

.calendar-day:hover {
  background-color: #f3f4f6;
}

.calendar-day.today {
  background-color: #ffffff;
  color: #429a9c;
  border: 2px solid #429a9c;
}

.calendar-day.selected {
  background-color: #429a9c;
  color: #ffffff;
}

.calendar-day.unavailable {
  color: #d1d5db; /* Gray out unavailable days */
  cursor: not-allowed;
  background-color: #ececec; /* 不能选择的日期背景色 */
}

.calendar-day.past-date {
  color: #9ca3af; /* 更浅的灰色 */
  cursor: not-allowed;
  background-color: #ececec; /* 不能选择的日期背景色 */
  opacity: 0.6; /* 降低透明度 */
}

.calendar-day.past-date:hover {
  background-color: #ececec; /* 悬停时不改变背景色 */
  cursor: not-allowed;
}

:deep(.custom-datepicker .dp__main) {
  background: transparent;
  border: none;
  box-shadow: none;
}

:deep(.custom-datepicker .dp__header) {
  background: transparent;
  border: none;
  padding: 0;
  margin-bottom: 16px;
}

:deep(.custom-datepicker .dp__header .dp__header_title) {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  text-align: center;
}

:deep(.custom-datepicker .dp__header .dp__arrow_button) {
  color: #6b7280;
  transition: color 0.2s;
}

:deep(.custom-datepicker .dp__header .dp__arrow_button:hover) {
  color: #429a9c;
}

:deep(.custom-datepicker .dp__weekdays) {
  background: transparent;
  border: none;
  padding: 0;
  margin-bottom: 8px;
}

:deep(.custom-datepicker .dp__weekdays .dp__weekday) {
  color: #6b7280;
  font-size: 12px;
  font-weight: 500;
  padding: 8px 0;
  text-align: center;
}

:deep(.custom-datepicker .dp__calendar) {
  background: transparent;
  border: none;
  padding: 0;
}

:deep(.custom-datepicker .dp__calendar .dp__calendar_row) {
  border: none;
}

:deep(.custom-datepicker .dp__calendar .dp__calendar_row .dp__cell) {
  border: none;
  padding: 0;
}

:deep(.custom-datepicker .dp__calendar .dp__calendar_row .dp__cell .dp__cell_inner) {
  border-radius: 50%;
  padding: 8px;
  font-size: 14px;
  color: #9ca3af;
  transition: all 0.2s;
  min-width: 32px;
  min-height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.custom-datepicker .dp__calendar .dp__calendar_row .dp__cell .dp__cell_inner:hover) {
  background-color: #f3f4f6;
  color: #374151;
}

:deep(.custom-datepicker .dp__calendar .dp__calendar_row .dp__cell .dp__cell_inner.dp__today) {
  background-color: #ffffff;
  color: #429a9c;
  border: 2px solid #429a9c;
}

:deep(.custom-datepicker .dp__calendar .dp__calendar_row .dp__cell .dp__cell_inner.dp__active_date) {
  background-color: #429a9c;
  color: #ffffff;
}

:deep(.custom-datepicker .dp__calendar .dp__calendar_row .dp__cell .dp__cell_inner.dp__range_end) {
  background-color: #ffffff;
  color: #429a9c;
  border: 2px solid #429a9c;
}

:deep(.custom-datepicker .dp__calendar .dp__calendar_row .dp__cell .dp__cell_inner.dp__range_start) {
  background-color: #ffffff;
  color: #429a9c;
  border: 2px solid #429a9c;
}

:deep(.custom-datepicker .dp__calendar .dp__calendar_row .dp__cell .dp__cell_inner.dp__in_between) {
  background-color: #ffffff;
  color: #429a9c;
  border: 2px solid #429a9c;
}

/* 确保日期选择器是内联显示 */

/* 隐藏浏览器默认的邮件验证提示 */
input[type="email"]::-webkit-validation-bubble-message,
input[type="email"]::-webkit-validation-bubble-arrow,
input[type="email"]::-webkit-validation-bubble {
  display: none !important;
}

/* 隐藏Firefox的验证提示 */
input[type="email"]:invalid {
  box-shadow: none;
}

/* 隐藏所有浏览器的验证提示 */
input[type="email"]:invalid::-webkit-validation-bubble-message,
input[type="email"]:invalid::-webkit-validation-bubble-arrow,
input[type="email"]:invalid::-webkit-validation-bubble {
  display: none !important;
}

/* 自定义邮件输入框的提示样式 */
input[type="email"]:focus::placeholder {
  color: #9ca3af;
  font-style: italic;
}

/* 父子级项目样式 */
.project-item {
  transition: all 0.3s ease;
}

.project-item:hover {
  transform: translateX(2px);
}

.child-project {
  position: relative;
}

.child-project::before {
  content: '';
  position: absolute;
  left: -12px;
  top: 50%;
  width: 8px;
  height: 1px;
  background-color: #429a9c;
}

.expand-button {
  transition: transform 0.3s ease;
}

.expand-button.expanded {
  transform: rotate(180deg);
}

/* 隐藏数字输入框的步进器 */
.no-spinner::-webkit-outer-spin-button,
.no-spinner::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.no-spinner {
  appearance: textfield;
  -moz-appearance: textfield;
}

</style>
